package com.example.chengzhengwei;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.example.chengzhengwei.RunData;
import com.example.chengzhengwei.utils.FileUtils;
import com.example.chengzhengwei.SerialPortHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class ExportOptionsActivity extends AppCompatActivity implements SerialPortHelper.SerialPortListener {
    private static final int PERMISSION_REQUEST_CODE = 1;
    private DatabaseHelper dbHelper;
    private SerialPortHelper serialHelper; // 新增串口助手
    private boolean isExporting = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_export_options);

        dbHelper = new DatabaseHelper(this);
        serialHelper = new SerialPortHelper(this); // 初始化串口助手
        serialHelper.setListener(this); // 设置监听器
        serialHelper.init(); // 初始化串口接收器

        // 检查并请求存储权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    PERMISSION_REQUEST_CODE);
        }

        setupButtonListeners();
    }

    private void setupButtonListeners() {
        Button buttonExportUsb = findViewById(R.id.button_export_usb);
        Button buttonExportSerial = findViewById(R.id.button_export_serial);
        Button buttonBack = findViewById(R.id.button_back);

        buttonExportUsb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exportDataToUsb();
            }
        });

        buttonExportSerial.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendDataToSerial();
            }
        });

        buttonBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void exportDataToUsb() {
        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            Toast.makeText(this, "缺少存储权限，无法导出数据", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取外部存储目录（包括U盘）
        List<File> storageDirs = FileUtils.getExternalStorageDirectories(this);

        if (storageDirs.isEmpty()) {
            Toast.makeText(this, "未找到可写入的存储设备", Toast.LENGTH_SHORT).show();
            return;
        }

        // 获取数据库数据
        List<RunData> runDataList = dbHelper.getRunData();

        if (runDataList == null || runDataList.isEmpty()) {
            Toast.makeText(this, "没有数据可导出", Toast.LENGTH_SHORT).show();
            return;
        }

        // 转换数据格式
        List<String[]> csvData = convertToCsvFormat(runDataList);

        // 尝试导出到每个存储设备
        boolean exportSuccess = false;
        for (File storageDir : storageDirs) {
            if (FileUtils.exportToCsv(csvData, storageDir)) {
                exportSuccess = true;
                Toast.makeText(this, "数据已成功导出到: " + storageDir.getAbsolutePath(), Toast.LENGTH_LONG).show();
                break;
            }
        }

        if (!exportSuccess) {
            Toast.makeText(this, "导出失败，请检查存储设备", Toast.LENGTH_SHORT).show();
        }
    }

    private List<String[]> convertToCsvFormat(List<RunData> runDataList) {
        List<String[]> csvData = new ArrayList<>();

        // 添加表头
        csvData.add(new String[]{"ID", "Channel", "Value", "Timestamp", "Minutes", "Seconds"});

        // 添加数据行
        for (RunData data : runDataList) {
            csvData.add(new String[]{
                    String.valueOf(data.getId()),
                    String.valueOf(data.getChannel()),
                    String.valueOf(data.getValue()),
                    String.valueOf(data.getTimestamp()),
                    String.valueOf(data.getMinutes()),
                    String.valueOf(data.getSeconds())
            });
        }

        return csvData;
    }

    // 新增：实现串口发送逻辑
    private void sendDataToSerial() {
        if (isExporting) {
            Toast.makeText(this, "正在导出中，请稍候...", Toast.LENGTH_SHORT).show();
            return;
        }

        isExporting = true;
        Toast.makeText(this, "准备导出数据到串口...", Toast.LENGTH_SHORT).show();

        // 获取数据库数据
        List<RunData> runDataList = dbHelper.getRunData();

        if (runDataList == null || runDataList.isEmpty()) {
            Toast.makeText(this, "没有数据可导出", Toast.LENGTH_SHORT).show();
            isExporting = false;
            return;
        }

        // 转换为 CSV 格式（复用原有方法）
        List<String[]> csvData = convertToCsvFormat(runDataList);

        // 构建完整 CSV 字符串
        StringBuilder csvBuilder = new StringBuilder();
        for (String[] row : csvData) {
            for (int i = 0; i < row.length; i++) {
                csvBuilder.append(row[i]);
                if (i < row.length - 1) {
                    csvBuilder.append(",");
                }
            }
            csvBuilder.append("\n");
        }
        String csvContent = csvBuilder.toString();

        // 检查串口连接状态
        if (!serialHelper.isConnected) {
            Toast.makeText(this, "正在连接串口设备...", Toast.LENGTH_SHORT).show();
            serialHelper.connect(); // 触发连接流程，回调会在 onConnected() 中处理
        } else {
            // 已连接，直接发送数据
            actualSendData(csvContent);
        }
    }

    // 实际执行数据发送
    private void actualSendData(String csvContent) {
        try {
            // 发送数据
            serialHelper.sendData(csvContent);
            Toast.makeText(this, "数据已发送至串口设备", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(this, "发送失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        } finally {
            isExporting = false;
        }
    }

    // 实现 SerialPortListener 接口方法
    @Override
    public void onConnected() {
        runOnUiThread(() -> {
            Toast.makeText(this, "串口连接成功，开始发送数据...", Toast.LENGTH_SHORT).show();

            // 获取数据库数据
            List<RunData> runDataList = dbHelper.getRunData();
            if (runDataList == null || runDataList.isEmpty()) {
                Toast.makeText(this, "没有数据可导出", Toast.LENGTH_SHORT).show();
                isExporting = false;
                return;
            }

            // 转换为 CSV 格式
            List<String[]> csvData = convertToCsvFormat(runDataList);

            // 构建完整 CSV 字符串
            StringBuilder csvBuilder = new StringBuilder();
            for (String[] row : csvData) {
                for (int i = 0; i < row.length; i++) {
                    csvBuilder.append(row[i]);
                    if (i < row.length - 1) {
                        csvBuilder.append(",");
                    }
                }
                csvBuilder.append("\n");
            }
            String csvContent = csvBuilder.toString();

            // 发送数据
            actualSendData(csvContent);
        });
    }

    @Override
    public void onDisconnected() {
        runOnUiThread(() -> {
            Toast.makeText(this, "串口已断开连接", Toast.LENGTH_SHORT).show();
            isExporting = false;
        });
    }

    @Override
    public void onError(String message) {
        runOnUiThread(() -> {
            Toast.makeText(this, "串口错误: " + message, Toast.LENGTH_SHORT).show();
            isExporting = false;
        });
    }

    @Override
    public void onDataReceived(byte[] data) {
        // 接收到来自串口的数据（如设备响应）
        runOnUiThread(() -> {
            String response = new String(data);
            Toast.makeText(this, "来自串口的响应: " + response, Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "存储权限已获取", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "存储权限被拒绝，无法导出数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 释放串口资源
        if (serialHelper != null) {
            serialHelper.release();
        }
    }
}